package org.example.seata.common.rabbitmq.config;

import org.example.seata.common.rabbitmq.handle.DefaultMessageFailHandler;
import org.example.seata.common.rabbitmq.handle.MessageFailHandler;
import org.example.seata.common.rabbitmq.util.MqUtil;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author hzq
 * @date 2021/11/29 17:15
 */
@EnableRabbit
@Configuration
public class RabbitTemplateConfiguration {

    @Bean
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
        connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.SIMPLE);
        connectionFactory.setPublisherReturns(true);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(MqUtil.buildCustomConfirmCallback());
        rabbitTemplate.setReturnsCallback(MqUtil.buildCustomReturnsCallback());
        return rabbitTemplate;
    }

    @Bean
    @ConditionalOnMissingBean(MessageFailHandler.class)
    public MessageFailHandler messageFailHandler() {
        return new DefaultMessageFailHandler();
    }
}
